package code;

import code.Product;
import code.ProductService;
import java.io.*;
import java.net.Socket;
import java.util.*;

public class EStoreClient {
    private final String serverHost;
    private final int serverPort;
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public EStoreClient(String serverHost, int serverPort) {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
    }

    public void start() {
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符
            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 3:
                    addToCart();
                    break;
                case 4:
                    viewCart();
                    break;
                case 99:
                    backupData();
                    break;
                case 5:
                    new ProductService().saveData(); // 退出前保存数据
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选项，请重新输入！");
            }
        }
    }

    // 数据文件备份
    private void backupData() {
        String srcPath = new ProductService().getDataFilePath();
        String destPath = srcPath + ".bak";
        try (FileInputStream fis = new FileInputStream(srcPath);
             FileOutputStream fos = new FileOutputStream(destPath)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("数据备份成功，备份文件: " + destPath);
        } catch (FileNotFoundException e) {
            System.out.println("备份失败: 源文件不存在");
        } catch (IOException e) {
            System.out.println("备份失败: " + e.getMessage());
        }
    }

    // 商城菜单
    private void showMenu() {
        System.out.println("\n欢迎来到商城---- ");
        System.out.println("1. 浏览所有商品");
        System.out.println("3. 添加商品到购物车");
        System.out.println("4. 查看购物车");
        System.out.println("99. 备份数据文件");
        System.out.println("5. 退出");
        System.out.print("请输入您的选择: ");
    }

    // 从服务器获取商品列表并展示
    private void browseProducts() {
        System.out.println("\n--- 商品列表 ---");
        try (Socket socket = new Socket(serverHost, serverPort);
             ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {

            oos.writeObject("GET_ALL_PRODUCTS");
            List<Product> products = (List<Product>) ois.readObject();
            if (products.isEmpty()) {
                System.out.println("商店里还没有商品。");
                return;
            }
            products.forEach(System.out::println);
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("获取商品列表失败: " + e.getMessage());
        }
    }

    // 添加商品到购物车
    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = new ProductService().findProductById(productId);
        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }
        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine();
        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    // 查看购物车
    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }
        double total = 0.0;
        ProductService productService = new ProductService();
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }

    public static void main(String[] args) {
        new EStoreClient("localhost", 8888).start();
    }
}